﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Wikimentation.Areas.Wikimentation.Models;

namespace Wikimentation.Areas.Wikimentation.Controllers
{
    public class MainController : Controller
    {
        public MainController()
        {
        }

        public ActionResult Index()
        {
            string path = Server.MapPath(Url.Content("~/App_Data/WikiContent/"));
            var pages = new WikiPage(path).GetWikiPages();

            return View(pages.RenderWikitags());
        }

        public ActionResult Edit(Guid id)
        {
            string path = Server.MapPath(Url.Content("~/App_Data/WikiContent/"));

            var page = new WikiPage(path).GetWikiPage(id);

            return PartialView(page);
        }

        [HttpPost]
        public ActionResult Edit(WikiPage page)
        {
            string path = Server.MapPath(Url.Content("~/App_Data/WikiContent/"));

            var pages = new WikiPage(path).UpdateWikiPage(page);
            return PartialView("WikiPageView", page.RenderWikitags());
        }

        [HttpPost]
        public ActionResult Create(WikiPage page)
        {
            string path = Server.MapPath(Url.Content("~/App_Data/WikiContent/"));

            var pages = new WikiPage(path).UpdateWikiPage(page);
           
            return PartialView("Index", pages.ToList().RenderWikitags());
        }

        public ActionResult Create()
        {
            string path = Server.MapPath(Url.Content("~/App_Data/WikiContent/"));
            var page = new WikiPage(path).CreateWikiPage();

            return PartialView("Create", page);
        }

        public ActionResult Delete(Guid id)
        {
            string path = Server.MapPath(Url.Content("~/App_Data/WikiContent/"));
            var pages = new WikiPage(path).GetWikiPages();
            var pagesToDel = pages.Where(x => x.Id == id);
            if (pagesToDel.Any())
            {
                pages.Remove(pagesToDel.First());
            }

            new WikiPage(path).SaveWikiPages(pages);

            return PartialView("Index", pages.RenderWikitags());
        }
    }
}
